package net.url;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

public class BinarySaver
{
	public static void main(String[] args)
	{
		try
		{
			URL root = new URL("http://www.baidu.com");
			saveBinaryFile(root);
		}
		catch (Exception e)
		{
		}
	}
	public static void saveBinaryFile(URL u) throws IOException
	{
		URLConnection uc = u.openConnection();
		String contentType = uc.getContentType();
		int contentLength = uc.getContentLength();
		if(contentType.startsWith("text/")||contentLength==-1)
		{
			throw new IOException("This is not a binary file");
		}
		InputStream raw = uc.getInputStream();
		InputStream in = new BufferedInputStream(raw);
		byte[] data = new byte[contentLength];
		int byteRead = 0;
		int offset = 0;
		while(offset<contentLength)
		{
			byteRead = in.read(data, offset, data.length-offset);
			offset+=byteRead;
		}
		in.close();
		if(offset != contentLength)
		{
		}
		String filename = u.getFile();
		filename = filename.substring(filename.lastIndexOf('/')+1);
		FileOutputStream fout = new FileOutputStream(filename);
		fout.write(data);
		fout.flush();
		fout.close();
	}
}
